from sqlmodel import Session, create_engine, select

from app.core.config import settings
from app.models import User, UserCreate
from app import  models,crud
from urllib.parse import quote_plus
DB_USER = "root"
DB_PASSWORD = "hqh#nF8KN@Y9"
DB_HOST = "172.56.2.112"
DB_PORT = 13307
DB_NAME = "air_ticket"

# 对密码进行URL编码
encoded_password = quote_plus(DB_PASSWORD)

# 构建安全的数据库连接URL
DATABASE_URL = f"mysql+pymysql://{DB_USER}:{encoded_password}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
engine = create_engine(DATABASE_URL, echo=False, pool_pre_ping=True, pool_size=10, max_overflow=20)
# engine = create_engine(str(settings.SQLALCHEMY_DATABASE_URI))


# make sure all SQLModel models are imported (app.models) before initializing DB
# otherwise, SQLModel might fail to initialize relationships properly
# for more details: https://github.com/fastapi/full-stack-fastapi-template/issues/28


async def init_db(session: Session) -> None:
    # Tables should be created with Alembic migrations
    # But if you don't want to use migrations, create
    # the tables un-commenting the next lines
    # from sqlmodel import SQLModel

    # from app.core.engine import engine
    # This works because the models are already imported and registered from app.models
    # SQLModel.metadata.create_all(engine)

    user = session.exec(
        select(User).where(User.email == settings.FIRST_SUPERUSER)
    ).first()
    if not user:
        user_in = UserCreate(
            email=settings.FIRST_SUPERUSER,
            password=settings.FIRST_SUPERUSER_PASSWORD,
            is_superuser=True,
            registrationMethod='邮件',
            status='启用',
            phone=''
        )
        user= await crud.User(db=session).create(data=user_in)
        
